package com.tuling.jvm;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * Created by chenhs on 2018/8/3.
 *
 * 【使用unsafe 分配本机内存】
 * VM Args：-Xmx20M -XX:MaxDirectMemorySize=10M
 *
 */
public class DirectMemoryOOM {

    private static final int _1MB = 1024 * 1024;

    public static void main(String[] args) throws Exception {
        Field unsafeField = Unsafe.class.getDeclaredFields()[0];
        unsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe) unsafeField.get(null);
        while (true){
            unsafe.allocateMemory(_1MB);
        }

        /**

         Exception in thread "main" java.lang.OutOfMemoryError
         at sun.misc.Unsafe.allocateMemory(Native Method)
         at com.tuling.jvm.DirectMemoryOOM.main(DirectMemoryOOM.java:19)

         */
    }

}
